package com.example.storage.service.impl;

import com.example.storage.domain.Storage;
import com.example.storage.mapper.StorageMapper;
import com.example.storage.service.StorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

@Service
public class StorageServiceImpl implements StorageService {

    @Autowired
    private StorageMapper storageMapper;

    @Transactional
    @Override
    public Boolean deduct(String commodityCode, int count) {
        Example example = new Example(Storage.class);
        example.setForUpdate(true); //行锁
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo(Storage.FILED_COMMODITY_CODE, commodityCode);
        Storage storage = storageMapper.selectOneByExample(example);
        if (storage == null) {
            return Boolean.FALSE;
        }

        criteria.andGreaterThanOrEqualTo(Storage.FILED_COUNT, count);
        Storage updatedStorage = new Storage();
        updatedStorage.setCount(storage.getCount() - count);
        int influenceCount = storageMapper.updateByExampleSelective(updatedStorage, example);
        return influenceCount == 1;
    }
}
